/**
 * 获取当前需要展示的课程
 * @param courseList {array} 章列表
 * @returns {object} 当前需要展示的课程对象
 */
export function getCurrentCurriculum(courseList) {
  return courseList
  // 根据courseList每一项的curriculum_list平铺数组
    .reduce((pre, course) => [...pre, ...course.curriculum_list], [])
    .find(c => c.is_study === 1) || courseList[0].curriculum_list[0]
}

/**
 * 将is_study === 1 的章节点isOpen设置为true，否则设置为false
 * 并将章名称、章索引、节索引添加到节对象的属性中
 * @param chapter {array} 章
 * @param chapterIndex {number} 章索引
 * @returns {array}
 */
function setProp(chapter, chapterIndex) {
  Object.assign(chapter, {
    isOpen: chapter.curriculum_list
      .some(curriculum => curriculum.is_study === 1),
    curriculum_list: chapter.curriculum_list
      .reduce((pre, curriculum, curriculumIndex) => [...pre, {
        chapter_name: chapter.chapter_name, // 章名称
        chapterIndex, // 章索引
        curriculumIndex, // 节索引
        ...curriculum
      }], [])
  })
  return chapter
}

/**
 * 章对象添加isOpen属性，节对象添加章属性
 * 如果没有isOpen都为false则将第一个章节点的isOpen设置为true
 * @param chapterList {array} 章列表
 * @returns {array} 添加了isOpen属性的章列表
 */
export function chapterSetProp(chapterList) {
  let setChapter = chapterList
    .reduce((pre, chapter, chapterIndex) =>
      [...pre, setProp(chapter, chapterIndex)], []
    )
  if (setChapter.every(c => c.isOpen === false)) {
    setChapter[0].isOpen = true
  }
  return setChapter
}
